// 专门用来管理维护于购物车相关的数据  在vuex中一个模块就是一个对象
export default {
	namespaced: true,
	state() {
		return {
			carts: uni.getStorageSync('carts') || []
		};
	},
	getters: {
		cartCount(state) {
			// 统计购物车中商品的个数
			return state.carts.reduce((total, item) => {
				return total += item.goods_number;
			}, 0);

		},
		TcartCount(state) {
			return state.carts.reduce((total, item) => {
				if (!item.goods_state) return total;
				return total += item.goods_number;
			}, 0);
		},
		allChecked(state) {
			// 是否全部商品的 goods_state 都为 true
			return state.carts.every((item) => item.goods_state);
		},
		amount(state) {
			return state.carts.reduce((total, item) => {
				//如果商品是未选中的状态 那么金额就不在累加
				if (!item.goods_state) return total;
				return total += item.goods_price * item.goods_number;
			}, 0);
		}
	},
	mutations: {
		decreaseCount(state, index) {
			//每次将商品数量加1
			if (state.carts[index].goods_number <= 1) return;
			--state.carts[index].goods_number;
			this.commit('m_cart/saveToStorage');
		},
		increaseCount(state, index) {
			//每次将商品数量加1
			state.carts[index].goods_number++;
			this.commit('m_cart/saveToStorage');
		},
		toggleAll(state, allChecked) {
			state.carts.forEach(item => item.goods_state = !allChecked);
			this.commit('m_cart/saveToStorage');
		},

		toggleState(state, index) {
			state.carts[index].goods_state = !state.carts[index].goods_state;
			this.commit('m_cart/saveToStorage');
		},
		addToCart(state, goods) {
			// 需要检测购物车中否存在了相同的商品
			const result = state.carts.find((item) => item.goods_id === goods.goods_id);
			if (result) {
				// 如果存在将其数量加 1
				console.log('有相同的商品');
				result.goods_number += 1;
			} else {
				console.log('没同有相同商品');
				// 否则追加新商品到购物车
				state.carts.push(goods);
			}

			// 存入本地
			this.commit('m_cart/saveToStorage');
		},
		// 将购物车的数据存入本地
		saveToStorage(state) {
			uni.setStorageSync('carts', state.carts);
		}
	}
};
